package com.bdqn.dao;

import com.bdqn.entity.Student;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * StudentDaoMySQLImpl
 *
 * @author LILIBO
 * @since 2022-04-26
 */
public class StudentDaoMySQLImpl implements StudentDao {

    private static Logger logger = LogManager.getLogger(StudentDaoMySQLImpl.class);

    /**
     * 添加学生
     *
     * @param student
     * @return
     */
    @Override
    public int insert(Student student) {
        // 定义SQL语句
        String sql = "insert into student(studentNo,loginPwd,studentName,sex,gradeID) values(?,?,?,?,?)";
        // 定义SQL语句问号处对应的参数
        Object[] params = {student.getStudentNo(), student.getLoginPwd(), student.getStudentName(), student.getSex(), student.getGradeID()};
        // 调用通用的增删改方法，传递SQL语句及对应的参数
        return BaseDao.executeUpdate(sql, params);
    }

    /**
     * 获得所有数据
     *
     * @return 学生对象集合
     */
    @Override
    public List<Student> selectAll() {
        // 需要返回的结果集
        List<Student> list = new ArrayList<>();

        // 定义SQL语句
        String sql = "select * from student";

        // 获得数据库连接对象
        Connection conn = BaseDao.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            logger.debug("SQL: " + sql);
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                // 有一行数据就创建一个新的对象
                Student student = new Student();
                // 将从数据库中获取的数据列设置到对象的属性中
                student.setStudentNo(rs.getInt("studentNo"));
                student.setLoginPwd(rs.getString("loginPwd"));
                student.setStudentName(rs.getString("studentName"));
                student.setSex(rs.getString("sex"));
                student.setGradeID(rs.getInt("gradeID"));
                student.setPhone(rs.getString("phone"));
                student.setAddress(rs.getString("address"));
                student.setBornDate(rs.getString("bornDate"));
                student.setEmail(rs.getString("email"));
                student.setIdentityCard(rs.getString("identityCard"));
                // 一行数据处理完毕，将对象添加到集合中
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源，关闭数据库连接
            BaseDao.closeAll(rs, pstmt, conn);
        }
        return list;
    }

}
